package com.niiwoo.civet.trade.service.local.newRefund.notify;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.dto.response.AccountBaseResponse;
import com.niiwoo.civet.account.service.AccountDubboService;
import com.niiwoo.civet.base.constant.OrgConstant;
import com.niiwoo.civet.trade.constant.DatePatternConstant;
import com.niiwoo.civet.trade.dao.entity.AdvanceConfig;
import com.niiwoo.civet.trade.dao.entity.RefundOrder;
import com.niiwoo.civet.trade.dao.entity.RefundWithholdOrder;
import com.niiwoo.civet.trade.dao.mapper.AdvanceConfigMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectInvestorPlanMapperExt;
import com.niiwoo.civet.trade.dao.mapper.RefundOrderMapperExt;
import com.niiwoo.civet.trade.dao.mapper.RefundWithholdOrderMapperExt;
import com.niiwoo.civet.trade.enums.TradeEmailEnum;
import com.niiwoo.civet.trade.service.local.mail.MailSendService;
import com.niiwoo.civet.trade.service.local.refund.CommonLocalService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 还款异常告警
 */
@Slf4j
@Service
public class RefundWarnMsgService {
	@Autowired
	private RefundOrderMapperExt refundOrderMapperExt;
	@Autowired
	private RefundWithholdOrderMapperExt refundWithholdOrderMapperExt;
	@Autowired
	private ProjectInvestorPlanMapperExt projectInvestorPlanMapperExt;
	@Autowired
	private MailSendService mainSendService;
	@Autowired
	private CommonLocalService commonLocalService;
	@Autowired
	private AdvanceConfigMapperExt advanceConfigMapperExt;
	@Reference(version = "1.0.0")
	private AccountDubboService accountDubboService;

	public void sendMessageForRefund(){
		Date currentDate = commonLocalService.getCurrentDate();
		List<RefundOrder> orderList = refundOrderMapperExt.selectHandingOver2HoursOrders();
		Map<String, Object> messageContent = new HashMap<>();

		if (!CollectionUtils.isEmpty(orderList)){
			List<Long> projectIds = new ArrayList<>();
			orderList.forEach(p->{projectIds.add(p.getProjectId());});
			if (projectIds.size()>0) {
				String message = "　　还款订单处理超时，请关注查看t_tc_refund_order，标的号:" + JSON.toJSONString(projectIds);
				messageContent.put("message1", messageContent.getOrDefault("message","")+message);
			}

		}
		List<RefundWithholdOrder> refundWithholdOrders = refundWithholdOrderMapperExt.selectHandingOverTimeOrders();
		if (!CollectionUtils.isEmpty(refundWithholdOrders)){
			List<Long> projectIds = new ArrayList<>();
			refundWithholdOrders.forEach(p->{projectIds.add(p.getProjectId());});
			if (projectIds.size()>0) {
				String message = "　　代扣还款订单处理超时，请关注查看t_tc_refund_withhold_order，标的号:" + JSON.toJSONString(projectIds) ;
				messageContent.put("message2", messageContent.getOrDefault("message","")+message);
			}
		}
		//1-4点统计当日待垫付金额
		if (new DateTime().getHourOfDay()==17 || new DateTime().getHourOfDay()==1 || new DateTime().getHourOfDay()==3 || new DateTime().getHourOfDay()== 4 ){
			log.info("统计待垫付金额,日切时间={}",currentDate);
			AccountBaseResponse accountBaseResponse = accountDubboService.loadAccountById(8L);//担保公司
			AdvanceConfig advanceConfig = advanceConfigMapperExt.selectByPrimaryKey(OrgConstant.NIIWOO_ORG_ID);
			Assert.notNull(advanceConfig,"机构配置不存在");
			List<Map<String,BigDecimal>> currentDateGuaranteeAmountList = projectInvestorPlanMapperExt.sumCurrentDateForGuaranteeTotalAll(currentDate,OrgConstant.NIIWOO_ORG_ID);
			//Map<String,BigDecimal> currentDateOverdue30DaysGuaranteeAmount = projectInvestorPlanMapperExt.sumCurrentDateForGuaranteeTotal(new DateTime(currentDate).minusDays(advanceConfig.getOverdueDays()).toDate(),"0");
			StringBuilder stringBuffer = new StringBuilder();
			stringBuffer.append("日切日期:");
			stringBuffer.append(DateFormatUtils.format(currentDate, DatePatternConstant.YYYY_MM_DD));
			stringBuffer.append("　　当时时间:");
			stringBuffer.append(DateFormatUtils.format(new Date(), DatePatternConstant.YYYY_MM_DD_HH_MM_SS));
			stringBuffer.append(",  ");
			stringBuffer.append("；担保公司余额:");
			stringBuffer.append(accountBaseResponse.getAvailableAmount());
			stringBuffer.append("。");
			BigDecimal totalMoney = BigDecimal.ZERO;
			for (Map<String, BigDecimal> currentDateGuaranteeMap : currentDateGuaranteeAmountList) {
				if (!CollectionUtils.isEmpty(currentDateGuaranteeMap)){
					stringBuffer.append("逾期"+currentDateGuaranteeMap.get("advanceOverdueDays")+"天待垫付本金:");
					stringBuffer.append(currentDateGuaranteeMap.get("capitalTotal"));
					stringBuffer.append("元，");
					stringBuffer.append("待垫付利息:");
					stringBuffer.append(currentDateGuaranteeMap.get("interestTotal"));
					stringBuffer.append("元；");
					totalMoney = totalMoney.add(currentDateGuaranteeMap.get("capitalTotal")
							.add(currentDateGuaranteeMap.get("interestTotal")));
				}
			}

			stringBuffer.append("；待垫付总金额=").append(totalMoney).append("元 " );
			messageContent.put("message3",messageContent.getOrDefault("message","")+stringBuffer.toString());
		}
		log.info("还款邮件通知内容：{}", JSON.toJSONString(messageContent));
		if (!CollectionUtils.isEmpty(messageContent)) {
			mainSendService.sendTemplateMail(TradeEmailEnum.REFUND, messageContent);
		}
	}


}